var newly = 0, uid, ws, spage, fid=0, mm = 0, sex = '男';
var pictype, hispic='', phispic='';
var upload_pic = [];
var pic_index = 1;
document.addEventListener('plusready',function(){
	plus.nativeUI.closeWaiting();
	ws = plus.webview.currentWebview();
	spage = ws.spage;
	var id = ws.aid;	//病例id
	fid = ws.fid;
	uid = plus.storage.getItem('uid');//用户id
	if(id){
		$('.addover').hide();
		$('input, textarea').attr('placeholder', '无...');
		$('.mui-title').text('病例');
		$('.ztime').show();
		$('.zheng').removeClass('mui-navigate-right');
		$.ajax({
			type:"get",
			url:apiRoot+"?m=home&c=medicinal&a=caseInfo&aid="+id,
			dataType : 'json',
			success :function(v){
				plus.nativeUI.closeWaiting();
//				console.log(JSON.stringify(v));
				if(v){
					
					$('.name').val(v.name);
					$("input[value="+v.sex+"]").attr('checked', true);
					if(v.sex=='男'){
						$('.nax div').eq(1).hide();
					}else{
						$('.nax div').eq(0).hide();
					}
					$('.age').val(v.age);
					$('.departments').hide();
					$('.departments').siblings('label').text('医院科室：'+v.departments);	//医院科室
					$('.zheng').text(v.aidsname);
					$('.ztime').text(v.ztime);
					$("input[value="+v.newly+"]").attr('checked', true);
					if(v.newly=='0'){
						$('.examine div').eq(1).hide();
					}else{
						$('.examine div').eq(0).hide();
					}
					if(v.hispic){
						var str1 = '';
						$.each(v.pic1, function(k, v) {
							str1 += '<img src="'+webRoot + v+'" data-preview-src="" data-preview-group="1" />';
						});
						$('.hispic').html(str1);
					}
					if(v.phispic){
						var str2 = ''; 
						$.each(v.pic2, function(k, v) {
							str2 += '<img src="'+webRoot + v+'" data-preview-src="" data-preview-group="2" />';
						});
						$('.phispic').html(str2);
					}
					$('textarea[name=history]').val(v.history);
					$('textarea[name=phistory]').val(v.phistory);	//既往史
					$('textarea[name=recipe]').val(v.recipe);
					$('textarea[name=effect]').val(v.effect);
				}
			},
			error :function(e){
				console.log(JSON.stringify(e));
				errortoast();
			}
		});
	}else{
		$('.departments').show();
		$('.addover').show();
		$('.time-data').show();
		$('.mui-title').text('添加病例');
		$('.bbs-pulish-img').append('<img src="../images/fly.png" class="uploadpic" />');
		$('input, textarea').attr('disabled', false)
		var d = new Date();
		var year = d.getFullYear();
		var month = d.getMonth()+1;
		var day = d.getDate();
		month = month < 10 ? '0'+month : month;
		day = day < 10 ? '0'+day : day;
		$('.time-data').html(year+"-"+month+'-'+day);
		$('input[name=radio]').click(function(){
			sex = $(this).val();
		})
		$('input[name=radio1]').click(function(){
			newly = $(this).val();
		})
		//加载医院科室
		$.ajax({
			type:"get",
			url:apiRoot+"/home/medicinal/offices",
			dataType :'json',
			success :function(data){
//				console.log(JSON.stringify(data))
				if(data.length > 0){
					var str = '';
					$.each(data, function(k, v) {
						str += '<option value="'+v.tid+'">'+v.classname+'</option>';
					});
//					$('select[name=offices]').html(str); 
					$('.departments').html(str);
				}
			},
			error :function(e){
				errortoast();
			}
		});
		//选择症状
		$('.aidsname').on('tap', function(){
			goNewPage('me-archives-home-wojiade.html',{spage:ws.id})
		})
	}
	if(spage == 'me-archives-home.html'){//我的档案
		fid = uid;
		mm = 1;
	}
	//上传症状图
	$('.uploadpic').on('tap', function(){
		pictype = $(this).parent().attr('id');
//		console.log(pictype);return;
		mui('#sheet1').popover('toggle');
	})
	//选择拍照添加
	$('.paizhao').on('tap', function(){
		getImage();
	})
	//选择相册添加
	$('.photo').on('tap', function(){
		appendByGalleryMul();
	})
	function getImage() {
		var cmr = plus.camera.getCamera();
		cmr.captureImage(function(path) {
			path = plus.io.convertLocalFileSystemURL(path);
			$('#'+pictype).append('<img src="file://'+path+'"/>');
			appendPic('file://'+path);
//			$('#'+pictype).parent().find('img').unbind('longtap');
//			$('#'+pictype).parent().find('img').on('longtap', longdel);
		}, function(err) {});
	}
	function appendByGalleryMul() {
		plus.gallery.pick( function(path){
			$('#'+pictype).append('<img src="'+path+'"/>');
			appendPic(path);
		}, function(error){}, {} );
	}
	function appendPic(p){
		upload_pic=[];		// 照片数组
		pic_index = 1;
		upload_pic.push({name:"uploadkey"+pic_index,path:p});
		pic_index++;
		uploadPic();
	}
	$('.addover').click(function(){
		console.log(hispic+" "+phispic);
		var name = $('.name').val();
		var age = $('.age').val();
		var departments = $('.departments').val();	//医院科室
		var aidsname = $('.aidsname').text();
		var ztime = $('.time-data').text();
		var histor = $('textarea[name=history]').val();
		var phistory = $('textarea[name=phistory]').val();	//既往史
		var recipe = $('textarea[name=recipe]').val();
		var effect = $('textarea[name=effect]').val();
		console.log(name+" "+sex+" "+age+" "+departments+" "+aidsname+" "+newly+" "+ztime+" "+histor+" "+phistory+" "+recipe+" "+effect);
		if(upload_pic.length > 0 && hispic == '' && !phispic == ''){
			toast('正在处理图片，请稍候重试');return;
		}
		if(!name.trim() || !age.trim()|| !departments.trim() || aidsname == '请选择症状' || ztime == '请选择时间' || !histor.trim() || !recipe.trim() || !effect.trim()){
			toast('请补全信息');return;
		}
		if(hispic != '')hispic = hispic.substr(3);
		if(phispic != '')phispic = phispic.substr(3);
		showWating();
		$.ajax({
			type:"get",
			url:apiRoot+"?m=home&c=medicinal&a=addCases",
			data :{
				uid :uid,
				name :name,
				sex :sex,
				age :age,
				departments :departments,
				aidsname :aidsname,
				newly :newly,
				ztime :ztime,
				hispic :hispic,
				phispic :phispic,
				history :histor,
				phistory :phistory,
				recipe :recipe,
				effect :effect,
				fid :fid,
				mm :mm
			},
			success : function(data){
				plus.nativeUI.closeWaiting();
				console.log(JSON.stringify(data));
				if(data > 0){
					toast('添加成功');
					over(data, aidsname, ztime, histor);
				}else{
					toast('添加失败');
				}
			},
			error :function(e){
				console.log(JSON.stringify(e));
			}
		});
	})
},false)
//将图片上传到服务器
function uploadPic(){
	var server = apiRoot + '?m=Home&c=member&a=uploadOne';
	var task = plus.uploader.createUpload(server,{method: "POST"},function(t, status) { 
		if (status == 200) {
			var pic = t.responseText;
			console.log(pic);
			if(pic.msg){
				errortoast(pic.msg);
				return;
			}
			if(pic == -1){
				toast('上传图片失败！');
			}else{
				if(pictype == 'pic1'){	//主诉及病史图片
					hispic += '|-|'+pic+'|,|';
					console.log(hispic);
				}else if(pictype == 'pic2'){	//既往史照片
					phispic += '|-|'+pic+'|,|';
				}
			}
		} else {
			toast('上传图片失败！');
			return;
		}
	});
	for(var i in upload_pic){
		var f=upload_pic[i];
		task.addFile(f.path,{key:f.name});
	} 
	task.start();
}
//bid->病例id，aidsname->病名，ztime->诊断时间，bing->病情描述
function over(bid, aidsname, ztime, bing){
	var parentid = plus.webview.getWebviewById(spage);
	mui.fire(parentid,'change',{bid:bid, aidsname:aidsname, ztime:ztime, bing:bing});
	//当前页关闭
	mui.back();
}
//病例症状
window.addEventListener('bingz', function(e){
	var str = e.detail.str;
	console.log(str);
	if(str)$('.aidsname').text(str);
}, false)
//长按删除图片
//function longdel(){
//	var _this = $(this);
//	if(!_this.hasClass('uploadPic')){
//		plus.nativeUI.confirm('确认删除该照片', function(e){
//			if(e.index == 1){
//				console.log('删除')
//				_this.remove();
//			}
//		}, null, ['取消', '确认'])
//	}
//}